﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Xenta.Utils;
using Xenta.Attributes;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.Commerce.Controllers
{
    [Authenticate, InRole("ADMIN")]
    public sealed class SalesItemController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public ActionResult GoTo(int? id, string sku)
        {
            if(!id.HasValue)
            {
                dynamic m = null;
                if(!String.IsNullOrWhiteSpace(sku))
                {
                    m = Svc.ProcessOperation("GetSalesItemBySKU", new
                    {
                        SKU = sku
                    });
                }
                if(m == null)
                    return HttpNotFound();
                id = JDM.Int32(m.EntityID);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, RestoreState]
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost, PersistState]
        public ActionResult Create(int sellerID, 
            int catalogItemID,
            string sku, 
            string price,
            string[] flags,
            string availableFrom,
            string availableTo)
        {
            try
            {
                var m = Svc.ProcessOperation("CreateSalesItem", new
                {
                    SellerID = sellerID,
                    CatalogItemID = catalogItemID,
                    SKU = sku,
                    Price = Svc.Price(price),
                    Flags = flags.Merge(","),
                    AvailableFrom = Svc.DateTime(availableFrom),
                    AvailableTo = Svc.DateTime(availableTo)
                });
                return RedirectToAction(Loc.Act("Edit").Set(new
                {
                    id = JDM.Int32(m.EntityID)
                }));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Create"));
        }

        [HttpGet, RestoreState]
        public ActionResult Edit(int id)
        {
            var m = Svc.ProcessOperation("GetSalesItem", new
            {
                EntityID = id,
            }, new
            {
                DisclosureLevel = "Entire"
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpPost, PersistState]
        public ActionResult Update(int id, 
            int sellerID,
            int catalogItemID,
            string sku,
            string price,
            string[] flags,
            string availableFrom,
            string availableTo)
        {
            try
            {
                Svc.ProcessOperation("UpdateSalesItem", new
                {
                    EntityID = id,
                    SellerID = sellerID,
                    CatalogItemID = catalogItemID,
                    SKU = sku,
                    Price = Svc.Price(price),
                    Flags = flags.Merge(","),
                    AvailableFrom = Svc.DateTime(availableFrom),
                    AvailableTo = Svc.DateTime(availableTo)
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpGet, PersistState]
        public ActionResult Delete(int id)
        {
            try
            {
                Svc.ProcessOperation("DeleteSalesItem", new
                {
                    EntityID = id
                });
                return RedirectToAction(Loc.Act("Index"));
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }
            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id
            }));
        }

        [HttpPost, PersistState]
        public ActionResult BulkAttributeUpdate(int itemID, IDictionary<String, String> attributes)
        {
            try
            {
                Svc.ProcessOperation("BulkUpdateSalesItemAttributes", new
                {
                    HolderID = itemID,
                    Attributes = attributes
                });
            }
            catch(Exception ex)
            {
                ModelState.AddModelError("API", ex);
            }

            return RedirectToAction(Loc.Act("Edit").Set(new
            {
                id = itemID
            }));
        }

        #endregion

        #region AJAX Actions

        [HttpPost]
        public ActionResult Grid(int? page,
            int? rows,
            string sord,
            string sidx,
            string searchTerm,
            int? sellerID,
            int? supplierID,
            int? categoryID,
            int? groupID,
            string availableOn,
            string salesFlagMask)
        {
            page = page.HasValue ? page.Value - 1 : 0;
            rows = rows.HasValue ? rows.Value : 30;
            sord = sord.Equals("desc") ? "Descending" : "Ascending";

            var m = Svc.ProcessOperation("SearchSalesItemsOverCatalog", new 
            {
                Term = new
                {
                    Expression = searchTerm
                },
                SellerID = sellerID,
                SupplierID = supplierID,
                CategoryID = categoryID,
                GroupID = groupID,
                AvailableOn = String.IsNullOrWhiteSpace(availableOn) 
                    ? (DateTime?)null 
                    : Svc.DateTime(availableOn),
                Index = page * rows,
                Count = rows,
                SalesFlagMask = salesFlagMask,
                SalesSortBy = new[] 
                {
                    sidx
                },
                SortDir = sord
            }, new
            {
                DisclosureLevel = "Base",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                var t = (i.CatalogItem.Translations as IEnumerable<dynamic>)
                    .SingleOrDefault(x => JDM.Int32(x.Language.EntityID) ==
                        JDM.Int32(Svc.Localization.Language.EntityID));
                data.Add(new[] { 
                    JDM.Int32(i.EntityID),
                    JDM.String(i.Seller.Account.Email),
                    t != null ? JDM.String(t.Name) : String.Empty,
                    JDM.String(i.SKU),
                    Svc.Price((decimal)JDM.Decimal(i.Price))
                });
            }

            return Json(new
            {
                pageIndex = page + 1,
                pageCount = Math.Ceiling(JDM.Double(m.TotalCount) / rows),
                totalCount = JDM.Int64(m.TotalCount),
                data = data.ToArray()
            });
        }

        [HttpPost]
        public ActionResult Autocomplete(string term, string flagMask)
        {
            var m = Svc.ProcessOperation("GetSalesItemDictionary", new
            {
                FlagMask = flagMask,
                Term = new
                {
                    Expression = String.Format("{0}%", term)
                },
                Count = 10
            });
            var data = new List<Object>();

            foreach(var i in m.Items)
            {
                data.Add(new
                {
                    id = JDM.String(i.Key),
                    value = JDM.String(i.Value)
                });
            }
            return Json(data.ToArray());
        }

        #endregion
    }
}
